package bitbot.core;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class BaseDataFetcher {
	
	//const
    private static final String GET="GET";
    private static final String PUT="PUT";
    private static final String POST="POST";
    private static final String ATTR_CONTENT_TYPE = "Content-Type";
    private static final String BINARY = "binary/octet-stream";
    private static final String PATH_DELIMITER = "/";

    private static final int HTTP_OK = 200;
    private static final int HTTP_NO_CONTENT = 204;//OK for Delete
    private static final int HTTP_NOT_FOUND = 404;//Not found
	
	protected String fetchPublicDataString(String url) throws IOException, ProtocolException {
		HttpURLConnection conn = openHttpConnection(url);
		conn.setRequestMethod(GET);
		conn.setRequestProperty(ATTR_CONTENT_TYPE, "");

		int code = -1;
		code = conn.getResponseCode();
		S.log("S3: Response code during downloading = " + code);

		if (code == HTTP_NOT_FOUND) {
			S.log("S3: File not found: ");
		}

		if (code != HTTP_OK) {
			S.log("S3: Failed with message: " + conn.getResponseMessage());
		}

		BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
		InputStreamReader r = new InputStreamReader(in);

		char[] buf = new char[256];
		int read = r.read(buf);
		StringBuilder builder = new StringBuilder();
		while (read > -1) {
			builder.append(buf, 0, read);
			read = r.read(buf);
		}
		String jsonString = builder.toString();
		return jsonString;
	}
	
	protected HttpURLConnection openHttpConnection(String urlString) throws IOException {
		URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout( 5000 );
        connection.setConnectTimeout( 5000 );
        return connection;
	}

}
